"""消息处理器"""

from datetime import datetime
from nonebot import on_message, logger
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent
from nonebot.rule import Rule
from sqlalchemy.orm import Session
from sqlalchemy import and_
from .database import get_db_session, MessageRecord, init_db
from .config import config


def is_group_message() -> Rule:
    """检查是否为群消息"""
    def _is_group_message(event: MessageEvent) -> bool:
        return isinstance(event, GroupMessageEvent)
    return Rule(_is_group_message)


# 消息监听器
message_handler = on_message(rule=is_group_message(), priority=99, block=False)


@message_handler.handle()
async def handle_message(bot: Bot, event: GroupMessageEvent):
    """处理群消息，更新消息计数"""
    try:
        # 初始化数据库
        init_db()
        
        # 获取消息信息
        group_id = str(event.group_id)
        user_id = str(event.user_id)
        
        # 如果不统计机器人消息且发送者是机器人，则跳过
        if not config.message_counter_track_bot and user_id == str(bot.self_id):
            return
        
        # 获取用户信息
        try:
            user_info = await bot.get_group_member_info(group_id=event.group_id, user_id=event.user_id)
            username = user_info.get('card') or user_info.get('nickname', str(user_id))
            user_avatar = f"http://q1.qlogo.cn/g?b=qq&nk={user_id}&s=640"
        except Exception:
            username = str(user_id)
            user_avatar = f"http://q1.qlogo.cn/g?b=qq&nk={user_id}&s=640"
        
        # 获取群信息
        try:
            group_info = await bot.get_group_info(group_id=event.group_id)
            group_name = group_info.get('group_name', str(group_id))
        except Exception:
            group_name = str(group_id)
        
        # 更新数据库
        with get_db_session() as session:
            # 查找现有记录
            record = session.query(MessageRecord).filter(
                and_(
                    MessageRecord.group_id == group_id,
                    MessageRecord.user_id == user_id
                )
            ).first()
            
            if record:
                # 更新现有记录
                record.today_count += 1
                record.week_count += 1
                record.month_count += 1
                record.year_count += 1
                record.total_count += 1
                record.username = username
                record.user_avatar = user_avatar
                record.group_name = group_name
                record.updated_at = datetime.now()
            else:
                # 创建新记录
                record = MessageRecord(
                    group_id=group_id,
                    user_id=user_id,
                    username=username,
                    user_avatar=user_avatar,
                    group_name=group_name,
                    today_count=1,
                    week_count=1,
                    month_count=1,
                    year_count=1,
                    total_count=1
                )
                session.add(record)
            
            session.commit()
            
    except Exception as e:
        logger.error(f"处理消息时发生错误: {e}")


async def get_user_info_safe(bot: Bot, group_id: int, user_id: int) -> tuple[str, str]:
    """安全获取用户信息"""
    try:
        user_info = await bot.get_group_member_info(group_id=group_id, user_id=user_id)
        username = user_info.get('card') or user_info.get('nickname', str(user_id))
        user_avatar = f"http://q1.qlogo.cn/g?b=qq&nk={user_id}&s=640"
        return username, user_avatar
    except Exception:
        return str(user_id), f"http://q1.qlogo.cn/g?b=qq&nk={user_id}&s=640"


async def get_group_info_safe(bot: Bot, group_id: int) -> str:
    """安全获取群信息"""
    try:
        group_info = await bot.get_group_info(group_id=group_id)
        return group_info.get('group_name', str(group_id))
    except Exception:
        return str(group_id)